import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

import javax.servlet.ServletContext;

import model.Fly;

import org.hibernate.Session;

public class StaticMethods
{
	public static String	PATH			= "http://localhost:8080/miat/jsp/";
	private static boolean	databaseInited	= false;

	public static String getHTML(ServletContext context, String urlToRead)
	{
		InputStream inputStream = context.getResourceAsStream(urlToRead);
		BufferedReader rd; // Used to read results from the web page
		String line; // An individual line of the web page HTML
		String result = ""; // A long string containing all the HTML
		try
		{
			rd = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((line = rd.readLine()) != null)
			{
				result += line;
			}
			rd.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}

	public static String MD5(String sessionid) throws NoSuchAlgorithmException
	{
		String plaintext = sessionid;
		MessageDigest m = MessageDigest.getInstance("MD5");
		m.reset();
		m.update(plaintext.getBytes());
		byte[] digest = m.digest();
		BigInteger bigInt = new BigInteger(1, digest);
		String hashtext = bigInt.toString(16);
		// Now we need to zero pad it if you actually want the full 32 chars.
		while (hashtext.length() < 32)
		{
			hashtext = "0" + hashtext;
		}
		return hashtext;
	}

	public static String[] getInsertQueries(ServletContext context)
	{
		InputStream inputStream = context.getResourceAsStream("/jsp/database/inserts.sql");
		String result = "";
		byte[] b = new byte[1024];
		try
		{
			while (inputStream.read(b) > 0)
			{
				result += new String(b);
			}
			inputStream.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		System.out.println(result);
		return result.split(";");
	}

	public Properties getFormProperties(ServletContext context, String modelName) throws IOException
	{
		Properties properties = new Properties();
		InputStream inputStream = context.getResourceAsStream("/WEB-INF/property/form/" + modelName + "Form.properties");
		properties.load(inputStream);
		return properties;
	}

	public String initForm(String modelName, Object object)
	{
		String action = modelName.toLowerCase();
		String formHTML = "<form action='" + action + "' method=POST>";

		return formHTML;
	}

	public static void initDb(Session session, ServletContext context)
	{
		if ( !databaseInited )
		{
			Connection connection;
			// //transaction ////transaction = session.begin////transaction();
			// //transaction.commit();
			try
			{
				Class.forName("com.mysql.jdbc.Driver").newInstance();
				String url = "jdbc:mysql://localhost/test";
				connection = DriverManager.getConnection(url, "root", "root");
				Statement statement = connection.createStatement();
				String[] queryArray = StaticMethods.getInsertQueries(context);
				for (String queryString : queryArray)
				{
					System.out.println(queryString);
					statement.executeUpdate(queryString);
				}
				connection.close();
			}
			catch (ClassNotFoundException e)
			{
				e.printStackTrace();
			}
			catch (SQLException e)
			{
				e.printStackTrace();
			}
			catch (Exception exception)
			{
				exception.printStackTrace();
			}
		}
	}

	public static int getDateDifference(Date date1, Date date2)
	{
		long diff = date1.getTime() - date2.getTime();
		int intDiff = (int) (diff / (1000 * 60 * 60));
		if ( intDiff < 0 )
			return intDiff * -1;
		return intDiff;
	}

	public static long getDateDifferenceByDay(Date date1, Date date2)
	{
		long dateMilliSec1 = date1.getTime();
		long dateMilliSec2 = date2.getTime();
		return (dateMilliSec1 - dateMilliSec2) / (24 * 60 * 60 * 1000);
	}

	public static long getDateDifferenceByHour(Date date1, Date date2)
	{
		long dateMilliSec1 = date1.getTime();
		long dateMilliSec2 = date2.getTime();
		return (dateMilliSec1 - dateMilliSec2) / (60 * 60 * 1000);
	}

	public static long getDateDifferenceByMinute(Date date1, Date date2)
	{
		long dateMilliSec1 = date1.getTime();
		long dateMilliSec2 = date2.getTime();
		return (dateMilliSec1 - dateMilliSec2) / (60 * 1000);
	}

	public static String getFormattedDate(Date date)
	{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		return sdf.format(date);
	}

	public static String getFormattedDateForHourAndMin(Date date)
	{
		return (new SimpleDateFormat("HH:mm")).format(date);
	}

	public static String getFormattedDateForDate(Date date)
	{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		return sdf.format(date);
	}

	public static String formatFloat(float f)
	{
		DecimalFormat format = new DecimalFormat("#.#");
		return format.format(f);
	}

	public static String getHTML(String urlToRead)
	{
		URL url; // The URL to read
		HttpURLConnection conn; // The actual connection to the web page
		BufferedReader rd; // Used to read results from the web page
		String line; // An individual line of the web page HTML
		String result = ""; // A long string containing all the HTML
		try
		{
			url = new URL(urlToRead);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			while ((line = rd.readLine()) != null)
			{
				result += line;
			}
			rd.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}

	public static int getDayOfMonth(int year, int month)
	{
		int date = 1;
		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month, date);
		return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
	}

	public static String getDayName(Calendar calendar)
	{
		String dayNames[] = (new DateFormatSymbols()).getWeekdays();
		return dayNames[calendar.get(Calendar.DAY_OF_WEEK)];
	}

	public static ArrayList<Integer> getYearList(Session session)
	{
		ArrayList<Integer> years = new ArrayList<Integer>();
		Fly fly = Fly.getLastFly(session);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		int startYear = 2012;
		int endYear;
		if ( fly == null )
			endYear = Integer.parseInt(sdf.format(new Date()));
		else
			endYear = Integer.parseInt(sdf.format(fly.getDate1()));

		for (int year = startYear; year <= endYear; year++)
		{
			years.add(year);
		}
		return years;
	}
}